/*
 * @Description: 上传
 * @Author: Rfan
 * @Date: 2022-05-03 10:12:22
 * @LastEditTime: 2023-02-07 17:05:57
 */

import { useEffect, useState } from 'react';
import { Button, message, Modal, Space, Steps, Typography, Upload } from 'antd';
import cs from 'classnames';
import classNames from 'classnames/bind';
import { UploadOutlined } from '@ant-design/icons';
import { fetchLevelByATId } from '@/api/archivesType';
import { saveFolderLevel, saveTemplateRelation } from '@/api/accession';
import { uploadPath } from '@/api/upload';
import { delItemById } from '@/utils/list';
import TransferTemplate from '@/components/TransferTemplate';
import { EnumTemplateTypes } from '@/view/system/TemplateManage/dictionaries';
import type { FC } from 'react';
import type { ICommonDialog } from '@/interfaces/global';
import type { UploadChangeParam } from 'antd/lib/upload';
import type { UploadFile } from 'antd/lib/upload/interface';
import type { InputStatus } from 'antd/es/_util/statusUtils';
import styles from '../../styles/uploadFolderDialog.module.scss';

const cx = classNames.bind(styles);
const { Step } = Steps;

interface UploadFolderDialogProps extends ICommonDialog {
  batchData: any;
}

const UploadFolderDialog: FC<UploadFolderDialogProps> = (props) => {
  const { visible, batchData, onClose } = props;
  console.log('folder data', batchData);
  // 当前step
  const [current, setCurrent] = useState(0);
  // 层级列表（不含组件级）
  const [levelList, setLevelList] = useState([]);
  // 选中的模板
  const [selectTemplate, setSelectTemplate] = useState(null);
  // 模板选择框状态
  const [templateState, setTemplateState] = useState<InputStatus>('');
  // 已经上传的层级
  const [fileList, setFileList] = useState([]);
  // 当前层级是否已上传标志
  const [currentUploaded, setCurrentUploaded] = useState(false);
  // 存储上传成功后返回的完整条目数据
  const [latestRecord, setLatestRecord] = useState({});

  useEffect(() => {
    if (visible) {
      // 获取档案类型下层级
      fetchLevelByATId(batchData.archiveTypeId).then((res) => {
        setLevelList(delItemById(0, res.data, 'level'));
      });
    }
  }, [visible]);

  useEffect(() => {
    if (visible && batchData && JSON.stringify(batchData) !== '{}') {
      setFileList(batchData.attItemsList);
    }
  }, [batchData]);

  useEffect(() => {
    if (visible && batchData && JSON.stringify(batchData) !== '{}' && levelList.length > 0) {
      setUploadedFlag();
    }
  }, [fileList, levelList]);

  useEffect(() => {
    setUploadedFlag();
  }, [current]);

  const setUploadedFlag = () => {
    setCurrentUploaded(
      fileList.find((item) => item.level === levelList[current].level)?.status || false
    );
  };

  /**
   * @description: 关闭弹窗
   */
  const onCancel = () => {
    if (JSON.stringify(latestRecord) === '{}') {
      onClose();
    } else {
      onClose(latestRecord);
    }
    setCurrent(0);
    setLevelList([]);
    setFileList([]);
    setCurrentUploaded(false);
    setLatestRecord({});
  };

  /**
   * @description 步骤条，前进一步
   */
  const next = () => {
    if (selectTemplate) {
      saveTemplateRelation({
        batchId: batchData.id,
        templateId: selectTemplate
      }).then(() => {
        setCurrent(current + 1);
      });
    } else {
      setTemplateState('error');
      message.error('请选择模板');
    }
  };

  /**
   * @description 步骤条，返回一步
   */
  const prev = () => {
    setCurrent(current - 1);
  };

  /**
   * @description: 上传变化回调
   * @param {any} info
   */
  const onChange = (info: UploadChangeParam<UploadFile>) => {
    const { file } = info;
    if (file.status === 'done') {
      saveExcel(file, file.response);
    }
  };

  const saveExcel = (file: UploadFile, res: any) => {
    const params: any = { batchId: batchData.id };
    params.folderAtt = {
      fileSize: file.size,
      fileUrl: res.data?.url || '',
      level: levelList[current].level,
      status: true
    };
    saveFolderLevel(params).then((res) => {
      console.log('save s', res.data);
      setLatestRecord(res.data);
    });
  };

  return (
    <Modal
      title="目录导入EXCEL"
      visible={visible}
      className={cx('upload-folder-dialog')}
      width={600}
      maskClosable={false}
      destroyOnClose
      onCancel={onCancel}
      footer={[
        <Button key="close" onClick={onCancel}>
          关闭
        </Button>,
        <>
          {current > 0 && (
            <Button key="prev" onClick={() => prev()}>
              上一步
            </Button>
          )}
        </>,
        <>
          {current < levelList.length - 1 && (
            <Button
              key="next"
              type="primary"
              onClick={() => {
                next();
              }}
            >
              下一步
            </Button>
          )}
        </>,
        <>
          {current === levelList.length - 1 && (
            <Button key="finish" type="primary" onClick={() => onCancel()}>
              完成
            </Button>
          )}
        </>
      ]}
    >
      <p>
        全宗{batchData.fonds?.fondName} - 档案类型
        {batchData.archiveType?.atName}
      </p>
      {current === 0 && (
        <Space className={cx('select-template__wrap')}>
          <h4>请选择模板</h4>
          <TransferTemplate
            tplType={EnumTemplateTypes.ExcelImport}
            value={selectTemplate}
            templateState={templateState}
            onChange={setSelectTemplate}
          />
        </Space>
      )}
      <div className={cx('steps-wrap')}>
        <Steps current={current}>
          {levelList.map((item) => (
            <Step key={item.level} title={item.levelName} />
          ))}
        </Steps>
        <div className="steps-content">
          <Typography.Text className={cx('step--title')}>
            请上传{levelList[current]?.levelName}条目
          </Typography.Text>
          {currentUploaded && <Typography.Text type="success">已上传</Typography.Text>}
          {levelList.map((item) => (
            <Upload
              key={item.level}
              accept=".xlsx,.csv,.xls"
              action={uploadPath}
              name="file"
              maxCount={1}
              className={cs(
                cx('upload-wrap'),
                levelList[current].levelName === item.levelName ? cx('upload--current') : null
              )}
              onChange={onChange}
            >
              <Button icon={<UploadOutlined />}>点击上传</Button>
            </Upload>
          ))}
        </div>
      </div>
    </Modal>
  );
};

export default UploadFolderDialog;
